// Copyright (c) 2009 Hypirinha contributers
// This program is made available under the terms of the MIT License.
package org.hypirinha.html.output.dom;

import static org.hypirinha.html.AttributeFactory.name;
import static org.hypirinha.html.ElementFactory.*;
import org.hypirinha.html.Text;
import org.hypirinha.html.elements.Body;
import org.hypirinha.html.output.DomAdapter;
import static org.hypirinha.html.output.dom.XPathEvaluator.xPath;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.w3c.dom.Document;

public class DomAdapterTest {
    
    @Test
    public void shouldHandleChildElements() {
        Document document = new DomAdapter().asDocument(div().contains(div()));

        assertTrue(xPath(document).bool("div/div"));
        assertEquals(2, xPath(document).integer("count(//*)"));
    }

    @Test
    public void shouldHandleTextNodes() {
        Document document = new DomAdapter().asDocument(li().contains(new Text("Hello")));

        assertEquals("Hello", xPath(document).string("/li/text()"));
    }

    @Test
    public void shouldHandleAttributes() {
        Document document = new DomAdapter().asDocument(input(name("sheep")));

        assertEquals("sheep", xPath(document).string("/input/@name"));
    }

    @Test
    public void shouldHandleMultipleChildElementsAtTheSameLevel() {
        Document document = new DomAdapter().asDocument(form().contains(fieldset().contains(input(name("sheep")), input(name("cheese")))));

        assertEquals(2, xPath(document).integer("count(/form/fieldset/input/@name)"));
        assertEquals("sheep", xPath(document).string("/form/fieldset/input[1]/@name"));
        assertEquals("cheese", xPath(document).string("/form/fieldset/input[2]/@name"));
    }

    @Test
    public void shouldHandleMultipleLevelsOfNestedElements() {
        Body body = body();
        body.div().ul().li();

        Document document = new DomAdapter().asDocument(body);
        assertTrue(xPath(document).bool("/body/div/ul/li"));
        assertEquals(4, xPath(document).integer("count(//*)"));
    }

    @Test
    public void shouldHandleMixedTextAndElementChildNodes() {
        Document document = new DomAdapter().asDocument(li().contains(new Text("Hello"), input(name("sheep"))));

        assertEquals("Hello", xPath(document).string("/li/text()"));
        assertEquals("sheep", xPath(document).string("/li/input/@name"));
    }
}